<template>
    <div class="login_box">
        <div class="text_login">
            <!-- logo -->
            <img class="login_logo" src="../../assets/img/logo/orange.png" />

            <!-- 表单区域 -->
            <van-form @submit="login">
                <van-field v-model="userPhone" name="手机号" label="手机号" placeholder="手机号"
                    :rules="[{ required: true, message: '请填写手机号' }]" />
                <van-field v-model="userCode" center clearable label="短信验证码" placeholder="请输入短信验证码">
                    <template #button>
                        <van-button :disabled="buffer" size="small" color="#FF6040" type="primary" native-type="button"
                            @click="getCode">{{ sendStr }}</van-button>
                    </template>
                </van-field>
                <div style="margin: 16px;">
                    <van-button round block type="info" color="#FF6040" native-type="submit">点击登录</van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>

<script>
import Cookies from 'js-cookie'
export default {
    data() {
        return {
            userPhone: "",//用户手机号码
            userCode: "",//用户输入的验证码
            sendStr: "获取验证码",//发送按钮文字
            buffer: false//发送开关
        };
    },
    mounted() {
        // 1.获取cookie中的验证码倒计时数据
        let time = Cookies.get('time')
        let countTime = Date.parse(time)//将标准时间转换成时间字符串
        // 2.如果存在倒计时数据就执行定时器
        if (countTime - Date.now() > 0) {
            this.buffer = true//禁用发送开关
            // 定义处理倒计时方法
            this.getTime(countTime)
        }
    },
    methods: {
        // 定义处理倒计时方法
        getTime(countTime) {
            let t = setInterval(() => {
                this.sendStr = `${Math.ceil((countTime - Date.now()) / 1000)}s发送`
                if (countTime - Date.now() <= 0) {
                    clearInterval(t)
                    this.sendStr = "获取验证码"
                    this.buffer = false
                }
            }, 1000);
        },

        // 发送短信验证码
        getCode() {
            // 1.获取手机号
            let phone = this.userPhone
            // 2.验证码手机号 test():bool
            if (!/^1[3456789]\d{9}/.test(phone)) {
                this.$notify({
                    type: 'warning',
                    message: '手机号格式有误！'
                }); return;
            }
            // 3.提交手机号
            this.$api.reqSendSms({ phone })
                .then(res => {
                    console.log(res)
                    // 检测验证码是否合法（是否正确：值 是否过期：生成时间）
                    localStorage.setItem("code", JSON.stringify({ value: res.code, time: Date.now() }))
                    // 按钮禁用
                    this.buffer = true
                    // 倒计时 60 | time(cookie)
                    let expires = new Date(Date.now() + 10000)//获取倒计时标准时间
                    Cookies.set('time', expires, { expires })//将倒计时时间写到cookie
                    let countTime = Date.parse(expires)//将标准时间转换成时间字符串
                    // 定义处理倒计时方法
                    this.getTime(countTime)
                })
                .catch(err => console.log(err))
        },

        // 执行登录
        login() {
            // 1.获取手机号
            let phone = this.userPhone
            // 2.验证码手机号 test():bool
            if (!/^1[3456789]\d{9}/.test(phone)) {
                this.$notify({
                    type: 'warning',
                    message: '手机号格式有误！'
                }); return;
            }
            // 3.验证验证码（值 过期）
            let userCode = this.userCode
            let { value, time } = JSON.parse(localStorage.getItem("code"))
            if (Date.now() - time > 50000) {
                this.$notify({
                    type: 'warning',
                    message: '验证码过期！'
                }); return;
            }

            if (userCode != value) {
                this.$notify({
                    type: 'warning',
                    message: '验证码输入有误！'
                }); return;
            }

            // 4.提交登录数据
            this.$api.reqSmsLogin({ phone })
                .then(res => {
                    // console.log(res)
                    // 3.存储用户信息到本地缓存中
                    localStorage.setItem("memberInfo", JSON.stringify(res))
                    // 4.提示登录成功
                    this.$notify({
                        type: 'success',
                        message: '登录成功！'
                    });
                    // 5.跳转到首页
                    this.$router.push('/')
                })
                .catch(err => console.log(err))


        }




    },
};
</script>

<style scoped>
.login_box {
    height: 100%;
    background-color: #f2f2f2;
    overflow: hidden;
}

.text_login {
    background-color: #FFFFFF;
    margin: 20px 20px 0;
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.login_logo {
    width: 364px;
    height: 96px;
    margin: 488px 0 88px 0;
}

.login_phone {
    height: 60px;
    width: 610px;
    border-bottom: 1px solid #CCCCCC;
    display: flex;
    color: #666666;
    font-size: 24px;
}

input {
    flex: 1;
    margin-left: 15px;
}

.login_code {
    height: 60px;
    width: 610px;
    border-bottom: 1px solid #CCCCCC;
    display: flex;
    justify-content: space-between;
    color: #666666;
    font-size: 24px;
    margin-top: 34px;

}

.login_code div {
    width: 160px;
    line-height: 48px;
    height: 48px;
    text-align: center;
    background-color: #CCCCCC;
    font-size: 20px;
    color: #FFFFFF;

}

.login_but {
    width: 610px;
    line-height: 49px;
    background-color: #FF6040;
    text-align: center;
    font-size: 32px;
    color: #FFFFFF;
    margin-top: 40px;
}
</style>
